<!DOCTYPE html>
<html>
<head>
    <title>订单管理</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="UTF-8">
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/bootstrap-table.min.css" rel="stylesheet">
    <style>
        /* 侧边栏样式 */
        .sidebar {
            position: fixed;
            top: 0;
            left: 0;
            bottom: 0;
            width: 200px;
            background-color: #f8f9fa;
            padding-top: 20px;
            z-index: 1000;
            box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
        }

        .sidebar .menu {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .sidebar .menu li {
            padding: 10px 20px;
        }

        .sidebar .menu li a {
            color: #333;
            text-decoration: none;
            display: block;
        }

        .sidebar .menu li a:hover {
            background-color: #e9ecef;
            color: #007bff;
        }

        .sidebar .menu li.active {
            background-color: #007bff;
        }

        .sidebar .menu li.active a {
            color: white;
        }

        /* 内容区域样式 */
        .content-wrapper {
            margin-left: 200px;
            padding: 20px;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .sidebar {
                width: 60px;
            }

            .sidebar .menu li {
                text-align: center;
            }

            .sidebar .menu li a {
                padding: 10px;
            }

            .content-wrapper {
                margin-left: 60px;
            }
        }

        /* 批量查询相关样式 */
        .batch-query-panel {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 20px;
        }

        .batch-query-panel h4 {
            margin-top: 0;
            color: #495057;
        }

        .query-status {
            margin-top: 10px;
            padding: 10px;
            border-radius: 4px;
            display: none;
        }

        .query-status.success {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }

        .query-status.error {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }

        .query-status.warning {
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
            color: #856404;
        }

        .query-status.info {
            background-color: #d1ecf1;
            border: 1px solid #bee5eb;
            color: #0c5460;
        }

        .spinning {
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }

        /* 用户信息显示样式 */
        .user-info {
            padding: 10px 20px;
            border-bottom: 1px solid #dee2e6;
            margin-bottom: 20px;
            background-color: #e9ecef;
        }

        .user-info .username {
            font-weight: bold;
            color: #495057;
        }

        .user-info .role {
            font-size: 12px;
            color: #6c757d;
        }
    </style>
</head>
<body>
<!-- 左侧菜单栏 -->
<div class="sidebar">
    <!-- 用户信息显示 -->
    <div class="user-info">
        <div class="username" id="currentUsername">加载中...</div>
        <div class="role" id="currentRole">加载中...</div>
        <button id="btn_logout" type="button" class="btn btn-sm btn-outline-secondary" style="margin-top: 5px;">
            <span class="glyphicon glyphicon-log-out"></span> 退出登录
        </button>
    </div>
    
    <ul class="menu">
        <li><a href="./product.html" data-target="product" id="menu-product">商品浏览</a></li>
        <li class="active"><a href="#" data-target="order">订单管理</a></li>
        <li class="admin-only" style="display: none;"><a href="./index.html" data-target="index">用户管理</a></li>
    </ul>
</div>

<!-- 内容区域 -->
<div class="content-wrapper">
    <!-- 批量查询面板 -->
    <div class="batch-query-panel">
        <h4><i class="glyphicon glyphicon-search"></i> 批量查询</h4>
        <div class="row">
            <div class="col-md-3">
                <button id="btn_batch_query" type="button" class="btn btn-success">
                    <span class="glyphicon glyphicon-download" aria-hidden="true"></span>批量查询所有订单
                </button>
            </div>
            <div class="col-md-3">
                <button id="btn_clear_data" type="button" class="btn btn-warning">
                    <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>清空数据
                </button>
            </div>
            <div class="col-md-6">
                <div id="queryStatus" class="query-status"></div>
            </div>
        </div>
    </div>

    <div class="panel panel-default">
        <div class="panel-heading">
            <h3 class="panel-title text-center">订单管理</h3>
        </div>
        <div class="panel-body">
            <div id="toolbar" class="btn-group">
                <button id="btn_edit" type="button" class="btn btn-primary">
                    <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>查看
                </button>
                <button id="btn_refresh" type="button" class="btn btn-info">
                    <span class="glyphicon glyphicon-refresh" aria-hidden="true"></span>刷新
                </button>
            </div>

            <table data-toggle="table" id="orderTable" data-height="400"
                   data-classes="table table-hover" data-striped="true"
                   data-pagination="true" data-side-pagination="server"
                   data-show-refresh="true" data-show-toggle="true"
                   data-show-columns="true" data-toolbar="#toolbar">
                <thead>
                <tr>
                    <th data-field="state" data-checkbox='true'></th>
                    <th data-field="id">订单ID</th>
                    <th data-field="orderTime">订单时间</th>
                    <th data-field="orderUser.username">客户姓名</th>
                    <th data-field="orderUser.address">送货地址</th>
                    <th data-field="totalMoney">金额总计</th>
                </tr>
                </thead>
            </table>
        </div>
    </div>

    <!-- 查看待办模态框 -->
    <div class="modal fade" id="detailModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-xl" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">订单详情</h5>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>订单编号：</label>
                                <input type="text" class="form-control" id="orderDetailId" readonly>
                            </div>
                            <div class="form-group">
                                <label>下单时间：</label>
                                <input type="text" class="form-control" id="orderDetailTime" readonly>
                            </div>
                            <div class="form-group">
                                <label>客户姓名：</label>
                                <input type="text" class="form-control" id="orderDetailUser" readonly>
                            </div>
                            <div class="form-group">
                                <label>联系电话：</label>
                                <input type="text" class="form-control" id="orderDetailPhone" readonly>
                            </div>
                            <div class="form-group">
                                <label>送货地址：</label>
                                <textarea class="form-control" id="orderDetailAddress" readonly rows="3"></textarea>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="table-responsive">
                                <table class="table table-bordered">
                                    <thead>
                                    <tr>
                                        <th>商品名称</th>
                                        <th>单价</th>
                                        <th>数量</th>
                                        <th>小计</th>
                                    </tr>
                                    </thead>
                                    <tbody id="orderItemList">
                                    </tbody>
                                </table>
                            </div>
                            <div class="form-group text-right">
                                <label>订单总额：</label>
                                <h3 id="orderTotalAmount">0.00</h3>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="js/jquery.min.js"></script>
<!--<script src="js/popper.min.js"></script>-->
<script src="js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="js/bootstrap-table.min.js"></script>
<script src="js/bootstrap-table-zh-CN.min.js"></script>
<script>
    // 全局变量
    let currentUser = null;
    let isAdmin = false;

    $(function () {
        // 检查用户权限
        checkUserPermission();
        
        // 侧边栏导航
        $('.sidebar-menu a').on('click', function(e) {
            e.preventDefault();
            let target = $(this).data('target');
            $('.sidebar-menu li').removeClass('active');
            $(this).parent().addClass('active');

            if (target === 'order') return;
            
            // 根据权限控制页面跳转
            if (target === 'index' && !isAdmin) {
                alert('您没有权限访问用户管理页面');
                return;
            }
            
            window.location.href = `${target}.html`;
        });

        // 初始化表格
        $('#orderTable').bootstrapTable({
            url: 'order/list',
            columns: [{
                field: 'state',
                checkbox: true
            }, {
                field: 'id',
                title: '订单号'
            }, {
                field: 'orderTime',
                title: '下单时间',
                formatter: dateFormatter
            }, {
                field: 'orderUser.username',
                title: '客户姓名'
            }, {
                field: 'orderUser.address',
                title: '送货地址'
            }, {
                field: 'totalMoney',
                title: '订单总额',
                formatter: moneyFormatter
            }],
            toolbar: '#toolbar',
            search: true,
            showRefresh: true,
            showToggle: true,
            showColumns: true,
            pagination: true,
            sidePagination: 'server',
            pageSize: 10,
            pageList: [10, 25, 50, 100],
            responseHandler: function(res) {
                return res;
            }
        });

        // 批量查询按钮点击事件
        $('#btn_batch_query').click(function() {
            batchQueryOrders();
        });

        // 清空数据按钮点击事件
        $('#btn_clear_data').click(function() {
            if (confirm('确定要清空当前表格数据吗？')) {
                $('#orderTable').bootstrapTable('removeAll');
                showQueryStatus('数据已清空', 'success');
            }
        });

        // 刷新按钮点击事件
        $('#btn_refresh').click(function() {
            $('#orderTable').bootstrapTable('refresh');
            showQueryStatus('数据已刷新', 'success');
        });

        // 查看详情
        $('#orderTable').on('check.bs.table', function (e, row) {
            loadOrderDetails(row.id);
        });

        // 时间格式化
        function dateFormatter(value) {
            if (!value) return '';
            return new Date(value).toLocaleString();
        }

        // 金额格式化
        function moneyFormatter(value) {
            if (!value) return '0.00';
            return parseFloat(value).toFixed(2);
        }

        // 批量查询订单
        function batchQueryOrders() {
            $('#btn_batch_query').prop('disabled', true).html('<span class="glyphicon glyphicon-refresh spinning"></span>查询中...');
            showQueryStatus('正在批量查询订单数据...', 'info');

            $.ajax({
                url: 'order/all',
                type: 'GET',
                dataType: 'json',
                success: function(data) {
                    if (data && data.length > 0) {
                        // 将数据加载到表格中
                        $('#orderTable').bootstrapTable('load', data);
                        showQueryStatus(`成功查询到 ${data.length} 条订单数据`, 'success');
                    } else {
                        showQueryStatus('未查询到任何订单数据', 'warning');
                    }
                },
                error: function(xhr, status, error) {
                    showQueryStatus('查询失败: ' + error, 'error');
                },
                complete: function() {
                    $('#btn_batch_query').prop('disabled', false).html('<span class="glyphicon glyphicon-download" aria-hidden="true"></span>批量查询所有订单');
                }
            });
        }

        // 显示查询状态
        function showQueryStatus(message, type) {
            const statusDiv = $('#queryStatus');
            statusDiv.removeClass('success error warning info').addClass(type).text(message).show();
            
            // 3秒后自动隐藏
            setTimeout(function() {
                statusDiv.fadeOut();
            }, 3000);
        }

        // 加载订单详情
        function loadOrderDetails(orderId) {
            $.get(`order/queryOrderById?id=${orderId}`)
                .done(data => {
                    if (data) {
                        $('#orderDetailId').val(data.id);
                        $('#orderDetailTime').val(dateFormatter(data.orderTime));
                        $('#orderDetailUser').val(data.orderUser ? data.orderUser.username : '');
                        $('#orderDetailPhone').val(data.orderUser ? data.orderUser.phone : '');
                        $('#orderDetailAddress').val(data.orderUser ? data.orderUser.address : '');

                        // 加载订单项
                        $.get(`order/findItemsByOrderId?id=${orderId}`)
                            .done(items => {
                                let itemsHtml = '';
                                let totalAmount = 0;
                                
                                if (items && items.length > 0) {
                                    items.forEach(item => {
                                        const subtotal = (item.price || 0) * (item.count || 0);
                                        totalAmount += subtotal;
                                        itemsHtml += `
                                            <tr>
                                                <td>${item.product ? item.product.productName : ''}</td>
                                                <td>${moneyFormatter(item.price)}</td>
                                                <td>${item.count || 0}</td>
                                                <td>${moneyFormatter(subtotal)}</td>
                                            </tr>
                                        `;
                                    });
                                }

                                $('#orderItemList').html(itemsHtml);
                                $('#orderTotalAmount').text(moneyFormatter(data.totalMoney || totalAmount));
                            });

                        $('#detailModal').modal('show');
                    }
                })
                .fail(error => {
                    alert('加载订单详情失败: ' + error);
                });
        }

        // 页面加载完成后自动执行批量查询
        setTimeout(function() {
            batchQueryOrders();
        }, 1000);

        // 退出登录按钮点击事件
        $('#btn_logout').click(function() {
            if (confirm('确定要退出登录吗？')) {
                localStorage.removeItem('currentUser');
                window.location.href = 'login.html';
            }
        });
    });

    // 检查用户权限
    function checkUserPermission() {
        // 从localStorage获取用户信息
        const userStr = localStorage.getItem('currentUser');
        if (userStr) {
            currentUser = JSON.parse(userStr);
            isAdmin = currentUser.username === 'admin';
            
            // 更新用户信息显示
            $('#currentUsername').text(currentUser.username);
            $('#currentRole').text(isAdmin ? '管理员' : '普通用户');
            
            // 根据权限显示/隐藏元素
            if (isAdmin) {
                $('.admin-only').show();
                $('#menu-product').text('商品管理');
            } else {
                $('.admin-only').hide();
                $('#menu-product').text('商品浏览');
            }
        } else {
            // 如果没有用户信息，跳转到登录页
            window.location.href = 'login.html';
        }
    }
</script>
</body>
</html>
